package handler

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"tie/api/register"
	"tie/initlist/cache"
	"tie/initlist/mysql"
	"tie/inits/model"
	"time"
)

func Center(r *gin.Context) {
	var req register.Center
	err := r.ShouldBind(&req)
	if err != nil {
		r.JSON(400, &Res{
			Code:    400,
			Message: "参数失败",
			Data:    nil,
		})
		return
	}
	center := model.Center{
		Img:       req.Img,
		Name:      req.Name,
		Topic:     req.Topic,
		GuanCount: req.GuanCount,
		FenCount:  req.FenCount,
	}

	key := fmt.Sprintf("center_add")
	marshal, err := json.Marshal(center)
	cache.Rdb.Set(cache.Ctx, key, marshal, time.Minute*5)

	mysql.DB.Debug().Create(&center)
	r.JSON(200, &Res{
		Code:    200,
		Message: "个人中心添加成功",
		Data:    center,
	})
}

func CenterUpdate(r *gin.Context) {
	var req register.Center
	err := r.ShouldBind(&req)
	if err != nil {
		r.JSON(400, &Res{
			Code:    400,
			Message: "参数失败",
			Data:    nil,
		})
		return
	}
	center := model.Center{
		Model:     gorm.Model{ID: uint(req.Id)},
		Img:       req.Img,
		Name:      req.Name,
		Topic:     req.Topic,
		GuanCount: req.GuanCount,
		FenCount:  req.FenCount,
	}
	key := fmt.Sprintf("center_update")
	marshal, err := json.Marshal(center)
	cache.Rdb.Set(cache.Ctx, key, marshal, time.Minute*5)

	mysql.DB.Debug().Where("id = ?", req.Id).Updates(&center)
	r.JSON(200, &Res{
		Code:    200,
		Message: "个人中心更新成功",
		Data:    center,
	})
}
